package com.cskaoyan.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 暂时一点用都没用的类
 * by hjl
 */
public class JsonUtils {
    private static ObjectMapper mapper = new ObjectMapper();
    static {
        //会自动忽略为null的值，在写的时候
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
    //对象转jason字符串
    public static String toJason(Object o) throws JsonProcessingException {
        return mapper.writeValueAsString(o);
    }
    //前端参数有问题会返回null
    //jason字符串转对象 //in谁传进来的请在外面自己关闭这里不管
    public static <T> T readJasonToObject(InputStream in, Class<T> tClass) {
        int length = 0;
        byte[] bytes = new byte[1024];
        T t = null;
        String jasonStr = "";
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            while ((length = in.read(bytes)) != -1) {
                out.write(bytes, 0, length);
            }
            out.flush();
            jasonStr = out.toString("UTF-8");//jasonStr不可能为null
            if (!"".equals(jasonStr.trim())) {
                t = mapper.readValue(jasonStr, tClass);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    public static <T> T readJasonToObject(String jsonStr, Class<T> tClass) {
        if (!"".equals(jsonStr.trim())) {
            try {
               T t = mapper.readValue(jsonStr, tClass);
               return t;
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
